package cn.hycat.leetcode.easy;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;

/**
 * @author : lzhycat
 * @date : 2022-09-01 18:44
 */
public class L144二叉树前序遍历 {

    class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(Objects.isNull(root)) return list;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            list.add(root.val);
            if(Objects.nonNull(root.right)) {
                stack.push(root.right);
            }
            if(Objects.nonNull(root.left)) {
                stack.push(root.left);
            }
        }
        return list;
    }
}
